package http;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.util.concurrent.CopyOnWriteArrayList;

public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    CopyOnWriteArrayList<HttpObject> list = new CopyOnWriteArrayList<>();

    public HttpServerHandler() {
        System.out.println(this + "创建 HttpServerHandler");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(this + "channelActive");
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(this + "channelInactive");
        super.channelInactive(ctx);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println(this + "channelReadComplete");
        super.channelReadComplete(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject httpObject) {
        list.add(httpObject);
        if (httpObject instanceof HttpMessage) {

        } else if (httpObject instanceof HttpContent) {
            if (httpObject instanceof LastHttpContent lastHttpContent) {

            } else if (httpObject instanceof DefaultHttpContent defaultHttpContent) {

            } else {
                System.out.println("类型异常 HttpContent");
            }
        }else {
            System.out.println("类型异常 HttpObject");
        }

//
//        ByteBuf content = Unpooled.copiedBuffer("Hello, World!", Charset.defaultCharset());
//        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
////        response.headers().set(HttpHeaderNames.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE);
//        response.headers().set(HttpHeaderNames.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE);
//        ctx.writeAndFlush(response).addListener(new ChannelFutureListener() {
//            @Override
//            public void operationComplete(ChannelFuture future) throws Exception {
//                System.out.println("结束：" + future.isSuccess());
//                Throwable cause = future.cause();
//                if (cause != null) {
//                    cause.printStackTrace();
//                }
//                future.channel().close();
//            }
//        });
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
